function reset_spectrum_form(){
	$("#sp_ri").val("");
	$("#sp_rtmin").val("");
	$("#sp_rtsec").val("");
	$("#sp_rtmils").val("");
	$("#spectrum_origin_id").val("1");
	$("#spectral_comments").val("");
	$("#spectral_peaks").val("");
	$("#chromatogram_id").val("");	
}

function delete_spectrum(spid){
	 new Messi('Are you sure you want to delete this spectrum?', {title: 'Buttons', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}],
                callback: function(val) { if (val == 'Y'){ 
			archive_spectrum(spid);
                        }}});
}

/*
Update needs to include compound_id
*/
function associate_compound_spectrum(lcobj){
	myLayout.close('west');
        if (isSpectrumFormValid() == false){
                new Messi('Spectrum origin id is required', {title: 'Validation error', autoclose:1500});
                return;
        }
	var selected = $("#chromatogram_id").val();
	var dfkey = "";
        for (var d in datafile_dictionary){
                if (selected == datafile_dictionary[d]){
                        dfkey = d;
                        break;
                }
        }
	var compound_id = $("#compound_id").val();
        var chromatogram_id = dfkey;//$("#chromatogram_id").val();
        var sp_ri = $("#sp_ri").val();
	//convert minutes and seconds into mils
	var rt_milli = 0;
	var mins_entered = $("#sp_rtmin").val();
	if (mins_entered != ""){
		rt_milli = parseInt(parseFloat(mins_entered)*60*1000);  
	}
	var secs_entered = $("#sp_rtsec").val();
        if (secs_entered != ""){
                rt_milli = rt_milli + parseInt(parseFloat(secs_entered)*1000);
        }
	var mils_entered = $("#sp_rtmils").val();
	if (mils_entered != ""){
                rt_milli = rt_milli + parseInt(mils_entered);
        }	
	var sp_rt = rt_milli + "";

        var sp_resolution = $("#sp_resolution").val();
        var spectrum_origin_id = $("#spectrum_origin_id").val();
	var spectral_comments = $("#spectral_comments").val();
	var spectral_peaks = $("#spectral_peaks").val();
        $("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
        $.ajax({
                                type: "POST",
                                url:  "/cgi-bin/metabobase/update_spectrum.cgi",
                                data: {
                                        'compound_id': compound_id,'chromatogram_id': chromatogram_id,'sp_ri': sp_ri, 'sp_rt':sp_rt, 'sp_resolution':sp_resolution, 'spectrum_origin_id':spectrum_origin_id, 'spectral_comments':spectral_comments, 'spectral_peaks':spectral_peaks
                                },
                                success: function(json)
                                {
                                        $("#compound_library_dialog").hide();
                                        if ($.parseJSON(json) == null){
                                                 new Messi('Error on update_spectrum.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
					var jo  = $.parseJSON(json);
					var addSpectrum = "<br><a href=javascript:show_compound_form('current')><font size='-2'>View Compound</font></a>&nbsp;<a href=javascript:show_spectrum_form(null)><font size='-2'>Add Spectrum</font></a>&nbsp;<a href=javascript:show_spectrum_annotation_form(null)><font size='-2'>Mass spectra</font></a>";
                                        $("#compound_form_msg").html("Spectrum '" + jo["_spid"] + "' added, continue compound association" + addSpectrum);
					$("#spectrum_form").hide();
					$("#compound_form").show();
					$("#reference_spectrum_id").val(jo["_spid"]);
					 //myLayout.close('east');
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
}

function isSpectrumFormValid(){
	//spectrum_origin_id must be numeric
	return true;
}

function hide_spectrum(){
        $("#spectrum_form").hide();
	myLayout.close('east');
	myLayout.close('west');
}


function add_datafile(callback){
        var newDataFiles = [];
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/get_datafile.cgi",
                data: {'search_input': null},
                success: function(json)
                        {
				if ($.parseJSON(json) == null){
                                	new Messi('Error on get_datafile.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
                                $("#compound_library_dialog").hide();
                                datafile_dictionary  = $.parseJSON(json);
                                for (var jkey in datafile_dictionary){
                                        newDataFiles.push(datafile_dictionary[jkey])
                                }
                                datafileTypeAhead.data('typeahead').source = newDataFiles;
                                callback();
                        },
                 error:function(xhr,err)
                       {
                                alert("Failed loading datafiles\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                       }
        });
}


function show_spectrum_form(sparr){
	//myLayout.close('west');
	var addAnnotation = "<br><a href=javascript:show_compound_form('current')><font size='-2'>View Compound</font></a>&nbsp;<a href=javascript:show_spectrum_annotation_form(null)><font size='-2'>Mass spectra</font></a>";
	reset_spectrum_form();
	$("#compound_form_msg").html("Adding spectrum for compound " + $("#compound_id").val() + addAnnotation);
	if (datafile_dictionary != {}){
		add_datafile(function() {
			$("#spectrum_form").show();	
			$("#compound_form").hide();
			$("#spectrum_annotation_form").hide();
		});
	}else{
                $("#spectrum_form").show();
                $("#compound_form").hide();
	}
}

function identify_df_key(){
	var val = $("#chromatogram_id").val();
	if (val == ""){
		$("#chromatogram_id").val("");
		return;
	}
	var selected = $("ul.typeahead.dropdown-menu").find('li.active').data('value');
        $("#chromatogram_id").val(selected);
        /*var dfkey = "";
        for (var d in datafile_dictionary){
        	if (selected == datafile_dictionary[d]){
                	dfkey = d;
                        break;
                }
        }
	*/
}

function dblclickCompoundSpectrum(){
	$('#compound_spectral_tbl tbody tr').unbind('dblclick').bind('dblclick', function () {
        	var selectedData = compoundSpectrumTable.fnGetData( this );
                var spId = selectedData[0];
		$.ajax({
                type: "GET",
                url:  "/cgi-bin/metabobase/get_mz_values.cgi?spectrum_id=" + spId,
                success: function(json)
                {
			if ($.parseJSON(json) == null){
                                                 new Messi('Error on get_mz_values.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
			var jo  = $.parseJSON(json);
			var spdArray = jo.aaData[0][0].split(":");
			plotMZIntensity(spdArray[0],spdArray[1],spdArray[2]);
			//show_spectrum_form(spdArray);
		},
		error: function(){
			alert("failed getting mz values for spectrum " + spId);
		}
		});
	});
}

function dblclickSpectrumAnnotation(){
        $('#spectrum_annotation_tbl tbody tr').unbind('dblclick').bind('dblclick', function () {
                var selectedData = spectrumAnnotationTable.fnGetData( this );
                var cId = selectedData[0];
	});
}

function processCompoundSpectrum(compoundSpecDiv, specAnnotationDiv, cid){
	$("#spec_dialog").html("<img src='images/demo_wait.gif' />");
        if (compoundSpectrumTable != undefined)
        	compoundSpectrumTable.fnClearTable();
	if (spectrumAnnotationTable != undefined)
		spectrumAnnotationTable.fnClearTable();
        $.ajax({
        	type: "GET",
                url:  "/cgi-bin/metabobase/get_compound_spectrum.cgi?compound_id=" + cid,
                success: function(json)
                {
                	$("#spec_dialog").hide();
                        if ($.parseJSON(json) == null){new Messi('Error on get_compound_spectrum.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
			var jo  = $.parseJSON(json);
			compound_spectrum_arr = jo.compoundSpectralData;
                        compoundSpectrumTable = $('#'+compoundSpecDiv ).dataTable( {
                        "bProcessing": true,
                        "bDestroy": true,
                        'bPaginate':false,
    			'bInfo':false,
			'bFilter':false,
			"aaData": jo.compoundSpectralData,
                        fnDrawCallback: function() {
				dblclickCompoundSpectrum();  
                        }
                        } );
			spectrum_annotation_arr = jo.spectralAnnotationData;
			spectrumAnnotationTable = $('#'+specAnnotationDiv ).dataTable( {
                        "bProcessing": true,
                        "bDestroy": true,
                        'bPaginate':false,
                        'bInfo':false,
                        'bFilter':false,
                        "aaData": jo.spectralAnnotationData,
                        fnDrawCallback: function() {
                                dblclickSpectrumAnnotation();
                        }
                        } );
                },
                error:function(xhr,err)
                                {
                                        alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
       });
}

function archive_spectrum(sid){
        if (compoundSpectrumTable != undefined)
                compoundSpectrumTable.fnClearTable();
        $("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/archive_metabobase.cgi",
                data: { 'spectrum_id': sid, 'datatype':'spectrum'},
                                success: function(json)
                                {
                                        $("#compound_library_dialog").hide();
                                        $("#compound_form_msg").html("Spectrum Archived for id " + sid);
                                        refresh_spectrum_list(sid);
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
}

function refresh_spectrum_list(sid){
        var annos = {};
        var ind = 0;
        for (arr in compound_spectrum_arr){
        	if (compound_spectrum_arr[arr][0] == sid){
                	break;
                }
        	ind++;
        }
        compound_spectrum_arr.splice(ind, 1);
        compoundSpectrumTable = $('#compound_spectral_tbl').dataTable( {
                        "bProcessing": true,
                        "bDestroy": true,
                        'bPaginate':false,
                        'bInfo':false,
                        'bFilter':false,
                        "aaData": compound_spectrum_arr,
                        fnDrawCallback: function() {
                                dblclickCompoundSpectrum();
                        }
        } );
}

